<template>
  <div class="image-uploader">
    <label class="upload-label" :class="{ 'has-image': previewUrl }">
      <input 
        type="file" 
        accept="image/*" 
        @change="handleFileSelect" 
        class="hidden-input"
      />
      
      <div class="upload-area" v-if="!previewUrl">
        <p>点击上传图片</p>
      </div>
      
      <div class="preview-container" v-else>
        <img :src="previewUrl" alt="预览图" class="preview-image" />
        <button 
          type="button" 
          class="remove-button" 
          @click="clearImage"
        >
          <i class="fa fa-times"></i>
        </button>
      </div>
    </label>
    
    <div class="image-info" v-if="fileName">
      <p>文件名: {{ fileName }}</p>
      <p>大小: {{ fileSize }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

// 响应式数据
const selectedFile = ref(null);
const previewUrl = ref('');

// 计算属性 - 文件名
const fileName = computed(() => {
  return selectedFile.value ? selectedFile.value.name : '';
});

// 计算属性 - 文件大小（格式化后）
const fileSize = computed(() => {
  if (!selectedFile.value) return '';
  
  const bytes = selectedFile.value.size;
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
});

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件');
    return;
  }
  
  // 更新状态
  selectedFile.value = file;
  previewUrl.value = URL.createObjectURL(file);
};

// 清除已选图片
const clearImage = () => {
  selectedFile.value = null;
  previewUrl.value = '';
  // 重置 input 以允许重复选择同一文件
  const fileInput = document.querySelector('.hidden-input');
  if (fileInput) {
    fileInput.value = '';
  }
};
</script>

<style scoped>
.upload-label {
  display: block;
  border: 1px dashed #ccc;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
}

.hidden-input {
  display: none;
}

.preview-container {
  position: relative;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
}

.remove-button {
  position: absolute;
  top: -10px;
  right: -10px;
  background-color: #fff;
  color: #333;
  border: 1px solid #ccc;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.image-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  font-size: 14px;
}
</style>    